import subprocess
import os,re,sys,json
from dotenv import load_dotenv
one_key_version = '25062301'
print(f'one_key版本{one_key_version}')
def run_command(command):
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    stdout, stderr = process.communicate()
    if 'requirement' in command:
        return stdout.strip()
    if process.returncode != 0:
        print(f"stdout: {stdout}")
        if 'working tree clean' in stdout:
            # exit()
            pass
        print(f"stderr: {stderr}")
    else:
        if stderr != '':
            print(stderr)
        print(stdout)
        return stdout.strip()


def generate_requirements():
    with open("requirements.txt", "w") as f:
        subprocess.run(["pip", "freeze"], stdout=f)
    # run_command('pip install pipreqs -i https://mirrors.aliyun.com/pypi/simple/')
    # run_command('pipreqs . --force --pypi-server https://mirrors.aliyun.com/pypi/simple/')
    # run_command('pipreqs . --force')


def is_git_repository():
    return os.path.exists('.git')
def git_push():
    # 初始化Git仓库
    if not is_git_repository():
        # 初始化Git仓库
        res = run_command("git init")
    else:
        print("Git仓库已经初始化。")

    # 添加远程仓库
    res = run_command('git remote').split('\n')
    if 'origin' in res:
        print("远程仓库已存在，跳过添加远程仓库步骤")
        pass
    else:
        remote_url = input("请输入远程仓库URL: ")
        run_command(f"git remote add origin {remote_url}")

    # 添加文件到暂存区
    run_command("git add .")

    # 提交文件到本地仓库
    commit_message = input("请输入提交信息: ")
    run_command(f"git commit -m \"{commit_message}\"")

    # 推送到远程仓库
    run_command("git push origin master")

def check_all_env():
    file_list = os.listdir()
    if '.env' in file_list and '.gitignore' in file_list:
        with open('.env', 'r') as f:
            env_info = f.read()
            # print(env_info)
            print('env_info found')
            if env_info  == '':
                print('env_info is empty')
            else:
                my_value = 'my_value'
                new_text = re.sub(r'(=\s*).*$', rf'\1{my_value}', env_info, flags=re.MULTILINE)
                with open('env_template', 'w') as f:
                    f.write(new_text)
                pass
    else:
        print('未创建.env或.gitigonre文件')
        exit()
    with open('.gitignore', 'r',encoding="utf-8") as f:
        con = f.read()
    con = con.split('\n')
    if '.env' in con:
        pass
    else:
        with open('.gitignore', 'a') as f:
            f.write('\n.env')


def one_key():
    check_gitignore()
    checkt_python_version()
    # run_command("pip freeze > requirements.txt")
    generate_requirements()
    # 加载 .env 文件
    load_dotenv()
    # 获取环境变量
    value = os.getenv('FYT_TEST')
    print(value)
    check_all_env()
    pop = input('1.push\n2.pull')
    if pop == '1':
        git_push()
    elif pop == '2':
        run_command("git pull origin master")

def checkt_python_version():
    try:
        current_version = '.'.join(
            [str(sys.version_info.major), str(sys.version_info.minor), str(sys.version_info.micro)])
        with open('python_version.json', 'r', encoding="utf-8") as f:
            res = f.read()
            res_version = json.loads(res)['python_version']
            print(res_version)
        if res_version == current_version:
            print("Python版本正确")
        else:
            print('当前环境版本', current_version)
            print("项目环境Python版本", res_version)
            print("版本不匹配，请使用Python3.8或更高版本")
            exit()
    except:
        print('当前环境版本', current_version)
        print('未指定项目python环境版本')
        pv = input('请输入python版本: ')
        with open('python_version.json', 'w', encoding="utf-8") as f:
            f.write(json.dumps({'python_version':pv}))

def check_gitignore():
    '''
    查询.idea和**/.idea是否在忽略中
    '''
    with open('.gitignore', 'r', encoding="utf-8") as f:
        res = f.read()
        # print(res)
    if '.idea/' not in res:
        with open('.gitignore', 'a') as f:
            f.write('\n.idea/')
    if '**/.idea/' not in res:
        with open('.gitignore', 'a') as f:
            f.write('\n**/.idea/')

if __name__ == "__main__":
    one_key()
